/****************************************************
 * Copyright (c) 2015 SJXT Technology Limited, All rights reserved.
 *
 * No part of this program may be reproduced, transmitted,
 * transcribed, stored in a retrieval system, or translated into any 
 * other computer languages in any form or by any means without the
 * prior written permission of:
 *
 *   SJXT.CO.LTD.
 *   540, JinNing Road, Xiangzhou Zhuhai, GD 
 *   P.R. China
 *   Tel:       (+86)756-2274333
 *   Fax:       (+86)756-2282339
 **************************************************/
package com.zhao.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * 
 * @author zhaowj
 * @date2018年3月14日 下午9:34:13
 */
public class XMLUtil {
    public static Map doXMLParse(String strxml) throws JDOMException,IOException {
		strxml =strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
		
		if(strxml==null||"".equals(strxml))
		{
			return null;
		}
		
		Map m = new HashMap();
		
		InputStream in=new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		SAXBuilder builder = new SAXBuilder();
		Document doc=builder.build(in);
		Element root= doc.getRootElement();
		List list=root.getChildren();
		Iterator it=list.iterator();
		while(it.hasNext())
		{
			Element e=(Element)it.next();
			String k=e.getName();
			String v="";
			List children=e.getChildren();
			if(children.isEmpty())
			{
				v=e.getTextNormalize();
			}
			else
			{
				v=XMLUtil.getChildrenText(children);
				
			}
			
			m.put(k, v);
				
		}
		
		//�ر���
		in.close();
		
		return m;
	}
    
    public static String getChildrenText(List children) {
		StringBuffer sb=new StringBuffer();
		if(!children.isEmpty())
		{
			Iterator it=children.iterator();
			while (it.hasNext()) {
				Element e=(Element)it.next();
				String name=e.getName();
				String value=e.getTextNormalize();
				List list=e.getChildren();
				sb.append("<"+name+">");
				if(!list.isEmpty())
				{
					sb.append(XMLUtil.getChildrenText(list));
				}		
				sb.append(value);
				sb.append("</"+name+">");
			}
		}
		return sb.toString();
	}
}
